const assert = require("assert");
const logger = require("./logger");

const enterprises = {
  collectionName: "enterprises",
  collection(db) {
    return db.collection(this.collectionName);
  },
  async initialize(db) {
    return await this.collection(db).createIndex(
      { id: 1 },
      { unique: true, dropDups: true }
    );
  },
  async addAll(db, enterprises) {
    const size = enterprises.length;
    const collection = this.collection(db);
    try {
      const result = await collection.insertMany(enterprises);
      assert.equal(size, result.result.n);
      assert.equal(size, result.ops.length);
    } catch (err) {
      logger.error(err);
      return false;
    }
    return true;
  },
  async queryAll(db) {
    assert.notEqual(db, null);
    const collection = this.collection(db);
    return await collection.find({}).toArray();
  },
};

const initializeCollections = async (db) => {
  const cols = [enterprises];
  for (const i in cols) {
    if (cols.hasOwnProperty(i)) {
      const col = cols[i];
      if (typeof col.initialize === "function") {
        await col.initialize(db);
      }
    }
  }
};

module.exports = {
  enterprises,
  initializeCollections,
};
